<?php

namespace App\Controller\Common;

use App\Base\BaseController;
use App\Base\Format;
use App\BaseExt\SmsTencent;
use App\Repository\UserRepository;
use Symfony\Component\Routing\Annotation\Route;

class SmsController extends BaseController
{

    /**
     * @Route("/send_sms",name="AppSendSms")
     */
    public function AppSendSms(UserRepository $repository)
    {

        if (!$phone = $this->getParamRequired("phone")) {return $this->json_out(400,"请输入手机号");}
        $is = new Format();
        if (!$is->isPhone($phone)) {
            return $this->json_out(400,"手机号错误");
        }

        $lastTime = $this->getUserCache("smsLastTime");
        if ($lastTime > time() - 18) {
            return $this->json_out(400,"操作太频繁");
        }
        $smsRecentCount = $this->getUserCache("smsRecentCount");
        $smsRecentDate = $this->getUserCache("smsRecentDate");
        if (!$smsRecentCount || $smsRecentDate != date("Ymd") ) {
            $smsRecentCount = 1;
        }else{
            $smsRecentCount++;
        }
        if ($smsRecentCount > 50) {
            return $this->json_out(400,"尝试次数超出上限");
        }

//        require_once __DIR__."/../../../BaseExt/Sms.php";
//        $sms = new \Sms();
        $rand = rand(1000,9999);
//        $sms->sendSms($phone,"SMS_174166578",array("code"=>$rand));
        $this->setUserCache("smsCode",$rand);
        $this->setUserCache("smsLastTime",time());
        $this->setUserCache("smsLastPhone",$phone);
        $this->setUserCache("smsRecentCount",$smsRecentCount);
        $this->setUserCache("smsRecentDate",date("Ymd"));

//        return $this->json_out(200,"已发送 $rand","$rand");
        $sms = new SmsTencent();
        $sms->sendSms($phone,"625032",$rand);

        return $this->json_out(200,"已发送","$rand");

    }

}
